package org.firecloud.h5fun.controller.servlet;

import java.io.IOException;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.firecloud.h5fun.model.CommonConfig;
import org.firecloud.h5fun.model.CommonQuery;
import org.firecloud.h5fun.model.javabean.ProjectBean;
import org.firecloud.h5fun.model.javabean.SearchQueryBean;

public class Search extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		Connection connection = null;
    	try {
    		CommonConfig config = (CommonConfig) req.getServletContext().getAttribute("commonConfig");
    		connection = config.getConn();
			String strColumnId = req.getParameter("columnId");
			String str = req.getParameter("str");
			String strOrderBy = req.getParameter("orderBy");
			String strDesc = req.getParameter("desc");
			String strIsRest = req.getParameter("reset");
			String strPage = req.getParameter("page");
			SearchQueryBean query = null;
			if(strIsRest == null){
				query =  (SearchQueryBean) req.getSession().getAttribute("searchQuery");
			}
			if(query == null){
				query = new SearchQueryBean();
			}
			
			if(strColumnId != null){
				try{
					query.setColumnId(Byte.parseByte(strColumnId));
				}catch(Exception e){
					query.setColumnId((byte)0);
				}
			}
			if(str != null){
				query.setStr(str);
			}
			if(strOrderBy != null){
				try{
					query.setOrderBy(Byte.parseByte(strOrderBy));
				}catch(Exception e){
					query.setOrderBy((byte)0);
				}
			}
			if(strDesc != null){
				query.setDesc(Byte.parseByte(strDesc));
			}
			int page = 0;
			if(strPage != null){
				try{
					page = Integer.parseInt(strPage);
				}catch(Exception e){
					page = 0;
				}
			}
			req.getSession().setAttribute("searchQuery",query);
			List<ProjectBean> projects = new ArrayList<ProjectBean>();
			int sum = CommonQuery.select_projects(connection,projects,query,config.getSearchPageSize(), page);
			req.setAttribute("resultSet", projects);
			req.setAttribute("currentPage",page);
			req.setAttribute("maxPage", (sum-1)/config.getSearchPageSize());
			req.setAttribute("resultSetSize",sum);
			connection.close();
			req.getRequestDispatcher("jsp/page-search.jsp").forward(req, resp);
		} catch (Exception e) {
			Logger.getRootLogger().error(e.toString());
			req.getRequestDispatcher("jsp/page-error.jsp").forward(req, resp);
		}finally {
			if(connection!=null){
				try {
					connection.close();
				} catch (Exception e) {
					Logger.getRootLogger().equals(e);
				}
			}
		}
	}
}
